package com.young.springboot.basic.controller.mail;


import com.young.springboot.basic.service.mail.MailService;
import com.young.springboot.basic.vo.mail.MailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author hyy
 */

@RestController
@RequestMapping("/mail")
public class MailController {
    @Autowired
    private MailService mailService;

    /**
     * 发送邮件的主界面
     */
    @GetMapping("/")
    public ModelAndView index() {
        //打开发送邮件的页面
        ModelAndView mv = new ModelAndView("mail/sendMail");
        //邮件发信人
        mv.addObject("from", mailService.getMailSendFrom());
        return mv;
    }


    /**
     * 发送邮件
     */
    @PostMapping("/send")
    public MailVo sendMail(MailVo mailVo, MultipartFile[] files) throws IOException {
        mailVo.setMultipartFiles(files);

        // 以下是为异步发送邮件所做的处理，主要是保持邮件附件的内容，防止springboot删除临时文件导致因文件找不到而报错
        byte[][] attachFileBytes = new byte[files.length][];
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            InputStream inputStream = file.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024]; //buff用于存放循环读取的临时数据
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                outStream.write(buff, 0, rc);
            }
            //合并之后的字节数组
            byte[] in_merge = outStream.toByteArray();
            attachFileBytes[i]=in_merge;
        }
        mailVo.setAttachFileBytes(attachFileBytes);
        return mailService.sendMail(mailVo);
    }
}
